package org.dreamwork.cai.spring;

import org.dreamwork.cai.srf.ServiceRouteTable;
import org.dreamwork.concurrent.Looper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * CAI 环境在 Spring Application Context 中的桥接器，负责监听 Spring Application Context
 * 创建和销毁的事件
 */
@Component
public class SpringBridge implements BeanFactoryPostProcessor, DisposableBean {
    private final Logger logger = LoggerFactory.getLogger (SpringBridge.class);

    private static ExecutorService executor;

    @Override
    public void destroy () {
        logger.info ("spring application context destroy");

        if (executor != null) {
            if (logger.isTraceEnabled ()) {
                logger.trace ("shutting down the executor");
            }
            executor.shutdownNow ();
            executor = null;
        }

        Looper.exit ();
    }

    @Override
    public void postProcessBeanFactory (ConfigurableListableBeanFactory factory) {
        logger.info ("spring application context post start");
    }

    @Bean
    public static ExecutorService createExecutor () {
        return executor = Executors.newCachedThreadPool ();
    }

    @Bean
    public static ServiceRouteTable createRouteTable () {
        return new ServiceRouteTable ();
    }
}